import React from 'react';
import { Table, Empty, Button } from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import type { ColumnsType, TableRowSelection } from 'antd/es/table';

// 通用数据表格组件属性
export interface DataTableProps<T = any> {
  columns: ColumnsType<T>;
  dataSource: T[];
  loading?: boolean;
  rowKey?: string | ((record: T) => string);
  rowSelection?: TableRowSelection<T>;
  pagination?: {
    current: number;
    pageSize: number;
    total: number;
    showSizeChanger?: boolean;
    showQuickJumper?: boolean;
    showTotal?: (total: number, range: [number, number]) => string;
    pageSizeOptions?: string[];
  };
  scroll?: { x?: number; y?: number };
  size?: 'small' | 'middle' | 'large';
  onChange?: (pagination: any, filters: any, sorter: any) => void;
  emptyText?: string;
  emptyDescription?: string;
  showAddButton?: boolean;
  addButtonText?: string;
  onAddClick?: () => void;
  hasFilters?: boolean;
}

// 通用数据表格组件
const DataTable = <T extends Record<string, any>>({
  columns,
  dataSource,
  loading = false,
  rowKey = 'id',
  rowSelection,
  pagination,
  scroll = { x: 1200 },
  size = 'middle',
  onChange,
  emptyText = '暂无数据',
  emptyDescription,
  showAddButton = false,
  addButtonText = '添加数据',
  onAddClick,
  hasFilters = false,
}: DataTableProps<T>) => {
  // 默认分页配置
  const defaultPagination = {
    showSizeChanger: true,
    showQuickJumper: true,
    showTotal: (total: number, range: [number, number]) =>
      `第 ${range[0]}-${range[1]} 条，共 ${total} 条`,
    pageSizeOptions: ['10', '20', '50', '100'],
    ...pagination,
  };

  // 空状态组件
  const renderEmpty = () => {
    const description = emptyDescription || (hasFilters ? '没有找到匹配的数据' : emptyText);
    
    return (
      <Empty
        image={Empty.PRESENTED_IMAGE_SIMPLE}
        description={description}
      >
        {showAddButton && !hasFilters && (
          <Button type="primary" icon={<PlusOutlined />} onClick={onAddClick}>
            {addButtonText}
          </Button>
        )}
      </Empty>
    );
  };

  return (
    <Table<T>
      columns={columns}
      dataSource={dataSource}
      rowKey={rowKey}
      rowSelection={rowSelection}
      loading={loading}
      onChange={onChange}
      pagination={pagination ? defaultPagination : false}
      scroll={scroll}
      size={size}
      locale={{
        emptyText: renderEmpty(),
      }}
    />
  );
};

export default DataTable;
